<?php

$loader->requireOnce('ordo/Department.class.php');
class C_RadAdmin extends Controller {
	private $logger;
	const LIST_TYPE_SERVICE        =   'service';
	const LIST_TYPE_GROUP          =   'group';
	const LIST_TYPE_ADD_SERVICE    =   'additional_service';
	function __construct($template_mod = "general") {
        parent::Controller();
        $this->setLayout('admin');
        $this->template_mod = $template_mod;
        $this->view->path = 'rad_admin';
        $this->logger = LoggerManager::getLogger('module.dept_rad.controllers.C_RadAdmin');
	}

	public function actionManagement() {
        return $this->view->render('management.html');
	}

	public function actionListRadServiceAjax() {
		$result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        // Radiology service group
        $radGroupList   =   ORDataObject::factory('RadGroup')->getRadGroupsByEnumRadType(false, true);
        $this->assign('radGroupList', $radGroupList);

        // Radiology service
        $serviceList    =   ORDataObject::factory('Service')->getServicesByItemType(Service::RADIOLOGY_TYPE);
        $serviceList    =   $this->makeShowingAvailable($serviceList);
        $this->assign('serviceList', $serviceList);

        // Start index
        $this->assign('index', 1);
        $result['result']   =   $this->view->render('rad_service_list.html');

        return json_encode($result);
	}

	private function makeShowingAvailable($list, $listType='service') {
        switch ($listType) {
        	case self::LIST_TYPE_SERVICE:
				foreach ($list as &$item) {
		            $item['price']  =   L10nHelper::renderCurrency($item['price']);
		            $status = L10nHelper::_("In Use_1");
		            if ($item['disabled'] > 0) {
		                $status = L10nHelper::_("Lock");
		            }
		            $item['disabled_text']   =   $status;
		        }
		        return $list;

        	case self::LIST_TYPE_GROUP:
        		foreach ($list as &$item) {
                    $item['enum_paraclinic_type_text']  =   Utils::getEnumTextByKey(
                        EnumerationConstant::PARACLINIC_TYPE, $item['enum_paraclinic_type']);
                }
                return $list;
        	case self::LIST_TYPE_ADD_SERVICE:
                foreach ($list as &$item) {
                    $item['enum_paraclinic_type_text']  =   Utils::getEnumTextByKey(
                        EnumerationConstant::PARACLINIC_TYPE, $item['enum_paraclinic_type']);
                    $item['price']  =   L10nHelper::renderCurrency($item['price']);
                    $status = L10nHelper::_("In Use_1");
                    if ($item['enabled'] <= 0) {
                        $status = L10nHelper::_("Lock");
                    }
                    $item['enabled_text']   =   $status;
                }
                return $list;
        }
	}

	public function actionSaveRadServiceAjax() {
		$result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $serviceId  =   $_POST['serviceId'];
        $this->logger->info("Start action SaveRadServiceAjax {serviceId=$serviceId}");
        $objService =   Celini::newORDO('Service', $serviceId);
        $data = array (
            'item_type'    =>   Service::RADIOLOGY_TYPE,
            'price'        =>   L10nHelper::getNumber($_POST['price']),
            'disabled'     =>   $_POST['disabled'],
            'department_id'=>   Department::RADIOLOGY_DEPT_ID
        );

        $id    =   $objService->get_id();
        $name           =   Utils::sanitizeText($_POST['serviceName']);

        if($id > 0){
            $field          =   L10nHelper::changeField(L10nHelper::getLocale(),"name");
            $data[$field]   =   $name;
        }
        // Service has no name, add new localized name
        else{
            $supported  =   L10nHelper::getSupportedLocales();
            foreach ($supported as $locale  =>  $country){
            	$locale          =   L10nHelper::changeField($locale,"name");
                $data[$locale]   =   $name;
            }
        }
        
        $objService->populateArray($data);
        $objService->persist();
        $servId = $objService->get_id();
        $status = L10nHelper::_("In Use_1");
        if ( $_POST['disabled'] > 0) {
            $status = L10nHelper::_("Lock");
        }

        $result['result']   =   array(
            'serviceId'     =>  $servId,
            'serviceName'   =>  $name,
            'price'         =>  L10nHelper::renderCurrency($objService->get_price()),
            'disabled'      =>  $_POST['disabled'],
            'disabledText'  =>  $status
        );
        $this->logger->info("Finish action SaveRadServiceAjax {serviceId=$serviceId}");

        return json_encode($result);
	}

	public function actionListRadGroupAjax() {
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        // Radiology types
        $radTypeList    =   ORDataObject::factory('ParacliniqueConfig')->getRadiologyTypes();
        $this->assign('radTypeList', $radTypeList);

        // Get all existing radiology groups
        $radGroupList   =   ORDataObject::factory('RadGroup')->getRadGroupsByEnumRadType(false, false);
        $radGroupList   =   $this->makeShowingAvailable($radGroupList, self::LIST_TYPE_GROUP);
        $this->assign('groupList', $radGroupList);
        $this->assign('index', 1);
        $result['result']   =   $this->view->render('rad_group_list.html');

        return json_encode($result);
	}

    public function actionSaveRadGroupAjax() {
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $groupId  =   $_POST['radGroupId'];
        $this->logger->info("Start action SaveRadGroupAjax {groupId=$groupId}");
        $objGroup =   Celini::newORDO('RadGroup', $groupId);
        $data = array (
            'enum_paraclinic_type' =>  $_POST['radType']
        );

        $id    	=   $objGroup->get_id();
        $name           =   Utils::sanitizeText($_POST['groupName']);
        
        if($id > 0){
            $field          =   L10nHelper::changeField(L10nHelper::getLocale(),"name");
            $data[$field]   =   $name;
        }
        // Service has no name, add new localized name
        else{
            $supported  =   L10nHelper::getSupportedLocales();
            foreach ($supported as $locale  =>  $country){
            	$locale         =   L10nHelper::changeField($locale,"name");
                $data[$locale]  =   $name;
            }
        }
        $objGroup->populateArray($data);
        $objGroup->persist();
        $grpId = $objGroup->get_id();
        $radTypeName    =   Utils::getEnumTextByKey(EnumerationConstant::PARACLINIC_TYPE, $_POST['radType']);
        $result['result']   =   array(
            'groupId'     =>  $grpId,
            'groupName'   =>  $name,
            'radType'     =>  $_POST['radType'],
            'radTypeName' =>  $radTypeName
        );
        $this->logger->info("Finish action SaveRadGroupAjax {groupId=$groupId}");

        return json_encode($result);
    }

    public function actionMapServiceToGroupAjax() {
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $this->logger->info("Start action actionMapServiceToGroupAjax");
        $radGroupList   =   ORDataObject::factory('RadGroup')->getRadGroupsByEnumRadType(false, true);
        $this->assign('radGroupList', $radGroupList);
        $result['result']    =   $this->view->render('service_group_map.html');
        $this->logger->info("Finish action actionMapServiceToGroupAjax");

        return json_encode($result);
    }

    public function actionGetGroupServicesAjax() {
    	$result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $radGroupId     =   EnforceType::int($_GET['radGroupId']);
        $objRadGroup    =   Celini::newORDO('RadGroup', $radGroupId);
        $this->assign('radGroupId', $radGroupId);
        $this->assign('groupName', $objRadGroup->getLocalizedText('name'));
        $objRadService  =   ORDataObject::factory('RadService');
        $unMappedServiceList    =   $objRadService->getUnMappedServices();
        $this->assign('unMappedServiceList', $unMappedServiceList);
        $mappedServiceList      =   $objRadService->getServicesByGroup($radGroupId);
        $this->assign('mappedServiceList', $mappedServiceList);
        $result['result']   =   $this->view->render('map_service_list.html');

        return json_encode($result);
    }

    public function actionAddServicesToGroup() {
    	$result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
    	$option		=	$_POST['option'];
    	$radGroupId	=	$_POST['radGroupId'];
    	$serviceList	=	split(",", $_POST['selectedSeviceIds']);
    	if ($option == 'add') {
    		foreach ($serviceList as $serviceId ) {
    			$objRadService	=	ORDataObject::factory('RadService')->getObject($radGroupId, $serviceId);
    			$objRadService->populateArray(
    				array(
    					'rad_group_id'	=>	$radGroupId,
    					'service_id'	=>	$serviceId
    				)
    			);
    			$objRadService->persist();
    		}
	   	}
	   	else if($option == 'remove'){
	   		$serviceList = implode(',', $serviceList);
	   		ORDataObject::factory('RadService')->deleteServices($radGroupId, $serviceList);
	   	}

	   	return json_encode($result);
    }

    public function actionListAdditionalServiceAjax() {
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
         // Radiology types
        $radTypeList    =   ORDataObject::factory('ParacliniqueConfig')->getRadiologyTypes();
        $this->assign('radTypeList', $radTypeList);
        $addServiceList =   ORDataObject::factory('RadAdditionalService')->getRadServicesByStatus();
        $addServiceList =   $this->makeShowingAvailable($addServiceList, self::LIST_TYPE_ADD_SERVICE);
        $this->assign('addServiceList', $addServiceList);
        $this->assign('index', 1);
        $result['result']  =   $this->view->render('rad_additional_service_list.html');

        return json_encode($result);
    }

    public function actionSaveAddServiceAjax() {
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $radAddServiceId    =   EnforceType::int($_POST['serviceId']);
        $this->logger->info("Start action SaveAddServiceAjax {radAddServiceId='$radAddServiceId'}");
        $objRadService      =   Celini::newORDO('RadAdditionalService', $radAddServiceId);
        $data = array (
            'enum_paraclinic_type'  =>  $_POST['radType'],
            'price'                 =>   L10nHelper::getNumber($_POST['price']),
            'enabled'               =>   $_POST['enabled']
        );

        $id =  $objRadService->get_id();
        $name           =   Utils::sanitizeText($_POST['serviceName']);
        $data       =   array();
        if($id > 0){
            $field          =   L10nHelper::getLocale();
            $field			=	L10nHelper::changeField($field, "name");
            $data[$field]   =   $name;
        }
        // Service has no name, add new localized name
        else{
            $supported  =   L10nHelper::getSupportedLocales();
            foreach ($supported as $locale  =>  $country){
            	$locale		=	L10nHelper::changeField($locale, "name");
                $data[$locale]  =   $name;
            }
        }
        
        $objRadService->populateArray($data);
        $objRadService->persist();
        // Service id
        $serviceId      = $objRadService->get_id();
        // Rad type
        $radTypeName    =   Utils::getEnumTextByKey(EnumerationConstant::PARACLINIC_TYPE, $_POST['radType']);
        // Enabled status
        $status = L10nHelper::_("In Use_1");
        if (EnforceType::int($_POST['enabled']) <= 0) {
            $status = L10nHelper::_("Lock");
        }
        $result['result']   =   array(
            'serviceId'     =>  $serviceId,
            'serviceName'   =>  $name,
            'radType'       =>  $_POST['radType'],
            'radTypeName'   =>  $radTypeName,
            'price'         =>  L10nHelper::renderCurrency($objRadService->getPrice()),
            'enabled'       =>  $_POST['enabled'],
            'enabledText'   =>  $status
        );
        $this->logger->info("Finish action SaveAddServiceAjax {radAddServiceId='$radAddServiceId'}");

        return json_encode($result);
    }
}
?>